<template>
  <ma-form-item
    v-if="typeof props.component.display == 'undefined' || props.component.display === true"
    :component="props.component"
    :custom-field="props.customField"
  >
    <slot :name="`form-${props.component.dataIndex}`" v-bind="props.component">
      <a-tree
        v-if="dictList[dictIndex] !== undefined"
        ref="menuRef"
        :data="dictList[dictIndex] ?? []"
        default-expand-all
        v-model:checked-keys="value"
        :field-names="props.component.fieldNames"
        checkable
        show-line
        class="tree-border"
      />
      <a-empty v-else class="tree-border" />
    </slot>
  </ma-form-item>
</template>

<script setup>
import { get, set } from "lodash";
import MaFormItem from "./form-item.vue";
import { runEvent } from "@/components/MaForm/types/event";
const menuRef = ref();
const props = defineProps({
  component: Object,
  customField: { type: String, default: undefined }
});
const formModel = inject("formModel");
const dictList = inject("dictList");
const getColumnService = inject("getColumnService");
const columns = inject("columns");
const rv = async (ev, value = undefined) =>
  await runEvent(
    props.component,
    ev,
    {
      formModel,
      getColumnService,
      columns
    },
    value
  );
const index = props.customField ?? props.component.dataIndex;
const dictIndex = index.match(/^(\w+\.)\d+\./)
  ? index.match(/^(\w+\.)\d+\./)[1] + props.component.dataIndex
  : props.component.dataIndex;
const value = ref(get(formModel.value, index));

menuRef.value?.internalSetCheckedKeys(value.value);
watch(
  () => get(formModel.value, index),
  vl => (value.value = vl)
);

watch(
  () => value.value,
  v => {
    set(formModel.value, index, v);
    index.indexOf(".") > -1 && delete formModel.value[index];
  }
);

rv("onCreated");
onMounted(() => rv("onMounted"));
</script>
<style lang="less" scoped>
.tree-border {
  border: 1px solid #e5e6e7;
  margin-top: 5px;
  border-radius: 4px;
  width: 100%;
  height: 150px;
  overflow-y: scroll;
}

:deep(.arco-empty-image) {
  padding-top: 25px;
}
</style>
